# -*- mode: python -*-
import os
import site
from pathlib import Path

from PyInstaller.utils.hooks import copy_metadata

block_cipher = None

prefix = Path("@prefix@")

# -----------------------------------------------------------------------------

# Gather directories with site packages
site_dirs = site.getsitepackages()
lib_dir = prefix / "lib"
for lib_python_dir in lib_dir.glob("python*"):
    site_dir = lib_python_dir / "site-packages"
    if site_dir.is_dir():
        site_dirs.append(site_dir)

# Look for compiled artifacts
binaries = []
for site_dir in site_dirs:
    for so_file in Path(site_dir).glob("**/*.so"):
        if not so_file.is_file():
            continue

        binaries.append((str(so_file), str(so_file.relative_to(site_dir).parent)))

# -----------------------------------------------------------------------------


def is_yes(s):
    """True if string is yes (from configure.ac)"""
    return s.lower().strip() == "yes"


# Options from ./configure
enable_fuzzywuzzy = is_yes("@ENABLE_FUZZYWUZZY@")
enable_wake_pocketsphinx = is_yes("@ENABLE_WAKE_POCKETSPHINX@")
enable_stt_pocketsphinx = is_yes("@ENABLE_STT_POCKETSPHINX@")
enable_kaldi = is_yes("@ENABLE_KALDI@")
enable_deepspeech = is_yes("@ENABLE_DEEPSPEECH@")
enable_snowboy = is_yes("@ENABLE_SNOWBOY@")
enable_porcupine = is_yes("@ENABLE_PORCUPINE@")
enable_precise = is_yes("@ENABLE_PRECISE@")
enable_snips = is_yes("@ENABLE_SNIPS@")
enable_raven = is_yes("@ENABLE_RAVEN@")
enable_larynx = is_yes("@ENABLE_LARYNX@")

# Add optional paths/imports
optional_pathex = []
optional_imports = []
optional_datas = []

if enable_fuzzywuzzy:
    optional_pathex.extend(["rhasspy-fuzzywuzzy", "rhasspy-fuzzywuzzy-hermes"])
    optional_imports.extend(
        ["rhasspyfuzzywuzzy.__main__", "rhasspyfuzzywuzzy_hermes.__main__"]
    )

if enable_wake_pocketsphinx or enable_stt_pocketsphinx:
    optional_imports.extend(["pocketsphinx"])

if enable_stt_pocketsphinx:
    optional_pathex.extend(
        ["rhasspy-asr-pocketsphinx", "rhasspy-asr-pocketsphinx-hermes"]
    )
    optional_imports.extend(
        ["rhasspyasr_pocketsphinx.__main__", "rhasspyasr_pocketsphinx_hermes.__main__"]
    )

if enable_kaldi:
    optional_pathex.extend(["rhasspy-asr-kaldi", "rhasspy-asr-kaldi-hermes"])
    optional_imports.extend(
        ["rhasspyasr_kaldi.__main__", "rhasspyasr_kaldi_hermes.__main__"]
    )

if enable_deepspeech:
    optional_pathex.extend(["rhasspy-asr-deepspeech", "rhasspy-asr-deepspeech-hermes"])
    optional_imports.extend(
        [
            "deepspeech",
            "rhasspyasr_deepspeech.__main__",
            "rhasspyasr_deepspeech_hermes.__main__",
        ]
    )

if enable_wake_pocketsphinx:
    optional_pathex.extend(["rhasspywake-pocketsphinx-hermes"])
    optional_imports.extend(["rhasspywake_pocketsphinx_hermes.__main__"])

if enable_snowboy:
    optional_pathex.extend(["rhasspy-wake-snowboy-hermes"])
    optional_imports.extend(["snowboy", "rhasspywake_snowboy_hermes.__main__"])
    optional_datas.extend(copy_metadata("snowboy"))

    # Add snowboy resources
    for site_dir in site_dirs:
        site_dir = Path(site_dir)
        resources_dir = site_dir / "snowboy" / "resources"
        if resources_dir.is_dir():
            optional_datas.extend(
                (str(p), str(p.relative_to(site_dir).parent))
                for p in resources_dir.rglob("*")
            )

if enable_porcupine:
    optional_pathex.extend(["rhasspy-wake-porcupine-hermes"])
    optional_imports.extend(["rhasspywake_porcupine_hermes.__main__"])

if enable_precise:
    optional_pathex.extend(["rhasspy-wake-precise-hermes"])
    optional_imports.extend(["rhasspywake_precise_hermes.__main__"])

if enable_snips:
    optional_pathex.extend(["rhasspy-snips-nlu", "rhasspy-snips-nlu-hermes"])
    optional_imports.extend(
        ["rhasspysnips_nlu.__main__", "rhasspysnips_nlu_hermes.__main__"]
    )

if enable_raven:
    optional_pathex.extend(["rhasspy-wake-raven", "rhasspy-wake-raven-hermes"])
    optional_datas.extend(copy_metadata("numpy"))
    optional_imports.extend(
        [
            "rhasspywake_raven.__main__",
            "rhasspywake_raven_hermes.__main__",
            "numpy",
            "scipy",
        ]
    )

if enable_larynx:
    optional_pathex.extend(
        [
            "rhasspy-tts-larynx-hermes",
            "rhasspy-tts-larynx-hermes/larynx/larynx",
            "rhasspy-tts-larynx-hermes/larynx/TTS",
        ]
    )

    optional_imports.extend(
        [
            "rhasspytts_larynx_hermes.__main__",
            "larynx",
            "TTS",
            "TTS.vocoder.models",
            "TTS.vocoder.models.multiband_melgan_generator",
            "TTS.tts.models",
            "TTS.tts.models.tacotron2",
            "TTS.tts.models.glow_tts",
            "TTS.tts.models.layers",
            "TTS.tts.models.layers.glow_tts.monotonic_align",
            "torch",
        ]
    )
    optional_datas.extend(copy_metadata("pyworld"))

# -----------------------------------------------------------------------------

a = Analysis(
    [Path.cwd() / "__main__.py"],
    pathex=[
        ".",
        "rhasspy-asr",
        "rhasspy-dialogue-hermes",
        "rhasspy-hermes",
        "rhasspy-homeassistant-hermes",
        "rhasspy-microphone-cli-hermes",
        "rhasspy-microphone-pyaudio-hermes",
        "rhasspy-nlu",
        "rhasspy-nlu-hermes",
        "rhasspy-profile",
        "rhasspy-remote-http-hermes",
        "rhasspy-server-hermes",
        "rhasspy-silence",
        "rhasspy-speakers-cli-hermes",
        "rhasspy-supervisor",
        "rhasspy-tts-cli-hermes",
    ]
    + optional_pathex,
    binaries=binaries,
    datas=copy_metadata("webrtcvad") + optional_datas,
    hiddenimports=[
        "aiofiles",
        "aiohttp",
        "networkx",
        "num2words",
        "pyaudio",
        "rhasspyasr",
        "rhasspydialogue_hermes.__main__",
        "rhasspyhermes.__main__",
        "rhasspyhomeassistant_hermes.__main__",
        "rhasspymicrophone_cli_hermes.__main__",
        "rhasspymicrophone_pyaudio_hermes.__main__",
        "rhasspynlu",
        "rhasspynlu.__main__",
        "rhasspynlu_hermes.__main__",
        "rhasspyprofile.__main__",
        "rhasspyrasa_nlu_hermes.__main__",
        "rhasspyremote_http_hermes.__main__",
        "rhasspyserver_hermes.__main__",
        "rhasspysilence.__main__",
        "rhasspyspeakers_cli_hermes.__main__",
        "rhasspysupervisor.__main__",
        "rhasspytts_cli_hermes.__main__",
    ]
    + optional_imports,
    hookspath=[],
    runtime_hooks=[],
    excludes=[],
    win_no_prefer_redirects=False,
    win_private_assemblies=False,
    cipher=block_cipher,
    noarchive=False,
)
pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)
exe = EXE(
    pyz,
    a.scripts,
    [],
    exclude_binaries=True,
    name="rhasspy",
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    console=True,
)
coll = COLLECT(
    exe, a.binaries, a.zipfiles, a.datas, strip=False, upx=True, name="rhasspy"
)
